<template>
	<el-dialog title="修改安装点设备" v-model="visible" :close-on-click-modal="false" draggable width="380px">
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="60px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="24" class="mb20">
					<el-form-item label="IMEI" prop="deviceId">
						<el-select
							v-model="form.deviceId"
							filterable
							remote
							reserve-keyword
							placeholder="请输入"
							remote-show-suffix
							:remote-method="remoteMethod"
							:loading="imeiLoading"
							@change="handleImeiChange"
						>
							<el-option v-for="item in imeiOptions" :key="item.id" :label="item.imei" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="EditImei">
import { replaceImei } from '/@/api/installation/basicInstallLocation';
import { fetchListAll, getObj as getDeviceObj } from '/@/api/platform/basicDevice';
import { useMessage } from '/@/hooks/message';
const emit = defineEmits(['refresh']);
type ListItem = {
	id: string;
	imei: string;
	deviceTypeId: string;
	deviceModelId: string;
};
const visible = ref(false);
const loading = ref(false);
const imeiLoading = ref(false);
const imeiOptions = ref<ListItem[]>([]);
// 提交表单数据
const form = reactive({
	id: '',
	deptId: '',
	imei: '',
	deviceId: '',
});

const dataFormRef = ref();
// 定义校验规则
const dataRules = ref({
	deviceId: [{ required: true, message: '请选择', trigger: 'change' }],
});

// 打开弹窗
const openDialog = (row: any) => {
	visible.value = true;
	form.id = row.id;
	form.deptId = row.deptId;
	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});
	remoteMethod(row.imei);
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;
	try {
		loading.value = true;
		await replaceImei(form);
		useMessage().success('修改成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 初始化表单数据
const remoteMethod = (query: string) => {
	if (query) {
		imeiLoading.value = true;
		fetchListAll({ imei: query, deptId: form.deptId })
			.then((res) => {
				imeiOptions.value = res.data;
			})
			.finally(() => {
				imeiLoading.value = false;
			});
	} else {
		imeiOptions.value = [];
	}
};
const handleImeiChange = (id: string) => {
	getDeviceObj(id).then((res) => {
		form.imei = res.data.imei;
	});
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss" scoped></style>
